package com.example.factory.api.facade.impl;

import com.example.factory.api.dto.DtoFactory;
import com.example.factory.api.dto.Response;
import com.example.factory.api.dto.form.DtoFactoryForm;
import com.example.factory.api.facade.FactoryFacade;
import com.example.factory.api.dto.assembler.FactoryAssembler;
import com.example.factory.core.domain.FactoryEntity;
import com.example.factory.core.repository.FactoryRepository;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Lei Tao
 */
@Service
public class FactoryFacadeImpl implements FactoryFacade {
    private final FactoryAssembler factoryAssembler;
    private final FactoryRepository factoryRepository;

    public FactoryFacadeImpl(FactoryAssembler factoryAssembler, FactoryRepository factoryRepository) {
        this.factoryAssembler = factoryAssembler;
        this.factoryRepository = factoryRepository;
    }

    @Override
    public Response<DtoFactory> updateFactory(DtoFactoryForm dtoFactoryForm) {
        FactoryEntity factoryEntity = factoryAssembler.toFactoryEntity(dtoFactoryForm);
        factoryRepository.save(factoryEntity);
        DtoFactory dtoFactory = factoryAssembler.toDtoFactory(factoryEntity);
        return Response.success(dtoFactory);
    }

    @Override
    public Response<DtoFactory> retrieveFactory() {
        List<FactoryEntity> factoryEntities = factoryRepository.selectFactories();
        DtoFactory dtoFactory = factoryAssembler.toDtoFactory(factoryEntities.get(0));
        return Response.success(dtoFactory);
    }
}
